/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClienteTela.java
 *
 * Created on 20/02/2011, 11:05:14
 */
package com.hd2tecnologia.telas;

import com.hd2tecnologia.entidades.ItensVenda;
import com.hd2tecnologia.entidades.Venda;
import com.hd2tecnologia.entidades.Cliente;
import com.hd2tecnologia.entidades.Produto;
import com.hd2tecnologia.modeloBanco.VendaBD;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;

/**
 *
 * @author Dulcyelliton Silva
 */
public class RegistraVendaTela extends javax.swing.JInternalFrame {

    private DefaultTableModel tableModel;
    private List<ItensVenda> itensVenda;
    private Produto produto;
    private Cliente cliente;

    public RegistraVendaTela() {
        initComponents();
        defineModelo();
        itensVenda = new ArrayList<ItensVenda>();
    }

    private void defineModelo() {
        tableModel = (DefaultTableModel) tblItensVenda.getModel();
        try {
            DecimalFormat formatoValor = new DecimalFormat("#,###.00");
            NumberFormatter formatterValor = new NumberFormatter(formatoValor);
            formatterValor.setValueClass(Double.class);
            ftfValorTotal.setFormatterFactory(new DefaultFormatterFactory(formatterValor));

            DecimalFormat formatoEstoque = new DecimalFormat("#,###");
            NumberFormatter formatterEstoque = new NumberFormatter(formatoEstoque);
            formatterEstoque.setValueClass(Integer.class);
            ftfQuantidade.setFormatterFactory(new DefaultFormatterFactory(formatterEstoque));

            tblItensVenda.getColumnModel().getColumn(0).setPreferredWidth(400);
        } catch (Exception ex) {
            Logger.getLogger(RegistraVendaTela.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void atualizaTabela() {
        int numeroLinhas = tblItensVenda.getRowCount();
        for (int i = 0; i < numeroLinhas; i++) {
            tableModel.removeRow(0);
        }
        double valorTotal = 0.0;
        for (int i = 0; i < itensVenda.size(); i++) {
            tableModel.insertRow(i, new Object[]{itensVenda.get(i).getProduto().getNome(),
            itensVenda.get(i).getQtde(),
            itensVenda.get(i).getProduto().getValor(),
            itensVenda.get(i).getProduto().getValor() * itensVenda.get(i).getQtde()
            });
            valorTotal += itensVenda.get(i).getProduto().getValor() * itensVenda.get(i).getQtde();
        }
        ftfValorTotal.setValue(valorTotal);
    }

    private void incluiProduto() {
        if (produto == null) {
            JOptionPane.showMessageDialog(this, "Selecionar o produto!", "Erro", JOptionPane.ERROR_MESSAGE);
            btnSelecionaProduto.requestFocus();
        } else if (ftfQuantidade.getValue() == null) {
            JOptionPane.showMessageDialog(this, "Informe a quantidade!", "Erro", JOptionPane.ERROR_MESSAGE);
        } else {
            ItensVenda item = new ItensVenda();
            item.setProduto(produto);
            item.setQtde((Integer) ftfQuantidade.getValue());
            item.setValor(produto.getValor());

            itensVenda.add(item);
            atualizaTabela();
        }
    }

    private void excluiProduto() {
        if (tblItensVenda.getSelectedRow() != -1){
            itensVenda.remove(tblItensVenda.getSelectedRow());
            atualizaTabela();
        }else{
            JOptionPane.showMessageDialog(this, "Selecione um item da lista!", "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void registarVenda(){
        if (getCliente() == null){
            JOptionPane.showMessageDialog(this, "Selecione um cliente!", "Erro", JOptionPane.ERROR_MESSAGE);
        }else if(itensVenda.isEmpty()){
            JOptionPane.showMessageDialog(this, "Insira itens na venda!", "Erro", JOptionPane.ERROR_MESSAGE);
        }else{
            Venda venda = new Venda();
            venda.setCliente(getCliente());

            Calendar dataAtual = Calendar.getInstance();
            venda.setDataVenda(new java.sql.Date(dataAtual.getTime().getTime()));

            venda.setItensVenda(itensVenda);

            VendaBD vendaBD = new VendaBD();
            if(vendaBD.registrarVenda(venda)){
                JOptionPane.showMessageDialog(this, "Venda registrada com sucesso!", "Informação", JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        ftfValorTotal = new javax.swing.JFormattedTextField();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtNomeCliente = new javax.swing.JTextField();
        btnSelecionaCliente = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblItensVenda = new javax.swing.JTable();
        jLabel7 = new javax.swing.JLabel();
        txtNomeProduto = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        ftfQuantidade = new javax.swing.JFormattedTextField();
        btnSelecionaProduto = new javax.swing.JButton();
        btnIncluiProduto = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        btnExcluiItem = new javax.swing.JButton();
        btnRegistraVenda = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("DSControl - Sistema de Gestão de Loja");
        setPreferredSize(new java.awt.Dimension(600, 400));
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 51, 153));
        jLabel1.setText("Registrar Venda");
        jPanel1.add(jLabel1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(jPanel1, gridBagConstraints);

        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        jLabel6.setText("Valor Total");
        jPanel2.add(jLabel6);

        ftfValorTotal.setPreferredSize(new java.awt.Dimension(70, 20));
        jPanel2.add(ftfValorTotal);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(jPanel2, gridBagConstraints);

        jPanel3.setLayout(new java.awt.GridBagLayout());

        jLabel2.setText("Cliente");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel3.add(jLabel2, gridBagConstraints);

        txtNomeCliente.setEditable(false);
        txtNomeCliente.setEnabled(false);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel3.add(txtNomeCliente, gridBagConstraints);

        btnSelecionaCliente.setText("...");
        btnSelecionaCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelecionaClienteActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel3.add(btnSelecionaCliente, gridBagConstraints);

        tblItensVenda.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Produto", "Qtde", "Vlr. Unit.", "Vlr. Total"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.Double.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tblItensVenda.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tblItensVenda);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 6;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weighty = 1.0;
        jPanel3.add(jScrollPane1, gridBagConstraints);

        jLabel7.setText("Produto");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel3.add(jLabel7, gridBagConstraints);

        txtNomeProduto.setEditable(false);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel3.add(txtNomeProduto, gridBagConstraints);

        jLabel3.setText("Qtde");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel3.add(jLabel3, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 50;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel3.add(ftfQuantidade, gridBagConstraints);

        btnSelecionaProduto.setText("...");
        btnSelecionaProduto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelecionaProdutoActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel3.add(btnSelecionaProduto, gridBagConstraints);

        btnIncluiProduto.setText("Incluir");
        btnIncluiProduto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIncluiProdutoActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel3.add(btnIncluiProduto, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(jPanel3, gridBagConstraints);

        jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        btnExcluiItem.setText("Excluir Item");
        btnExcluiItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluiItemActionPerformed(evt);
            }
        });
        jPanel4.add(btnExcluiItem);

        btnRegistraVenda.setText("Salvar");
        btnRegistraVenda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegistraVendaActionPerformed(evt);
            }
        });
        jPanel4.add(btnRegistraVenda);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(jPanel4, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSelecionaClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionaClienteActionPerformed
        ClienteTela clienteFrame = new ClienteTela(this);
        clienteFrame.setVisible(true);
        this.getDesktopPane().add(clienteFrame);
        clienteFrame.toFront();
    }//GEN-LAST:event_btnSelecionaClienteActionPerformed

    private void btnExcluiItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluiItemActionPerformed
        excluiProduto();
    }//GEN-LAST:event_btnExcluiItemActionPerformed

    private void btnRegistraVendaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistraVendaActionPerformed
        registarVenda();
    }//GEN-LAST:event_btnRegistraVendaActionPerformed

    private void btnIncluiProdutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIncluiProdutoActionPerformed
        incluiProduto();
    }//GEN-LAST:event_btnIncluiProdutoActionPerformed

    private void btnSelecionaProdutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionaProdutoActionPerformed
        ProdutoTela produtoFrame = new ProdutoTela(this);
        produtoFrame.setVisible(true);
        this.getDesktopPane().add(produtoFrame);
        produtoFrame.toFront();
    }//GEN-LAST:event_btnSelecionaProdutoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExcluiItem;
    private javax.swing.JButton btnIncluiProduto;
    private javax.swing.JButton btnRegistraVenda;
    private javax.swing.JButton btnSelecionaCliente;
    private javax.swing.JButton btnSelecionaProduto;
    private javax.swing.JFormattedTextField ftfQuantidade;
    private javax.swing.JFormattedTextField ftfValorTotal;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblItensVenda;
    private javax.swing.JTextField txtNomeCliente;
    private javax.swing.JTextField txtNomeProduto;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the produto
     */
    public Produto getProduto() {
        return produto;
    }

    
    public void setProduto(Produto produto) {
        this.produto = produto;
        txtNomeProduto.setText(produto.getNome());
    }

    
    public Cliente getCliente() {
        return cliente;
    }

    
    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
        txtNomeCliente.setText(cliente.getNome());
    }
}
